package com.hyw.supply.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hyw.supply.model.entity.SupplyItem;
import com.hyw.supply.model.excel.SupplyItemExcel;
import com.hyw.supply.model.query.OrderListQuery;
import com.hyw.supply.model.vo.CommonResult;
import com.hyw.supply.service.SupplyItemService;
import com.hyw.supply.utils.CustomToken;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.rmi.RemoteException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zzp
 * @since 2024-03-15
 */
@RestController
@RequestMapping("/excel")
@RequiredArgsConstructor
@Tag(name = "代理发货订单导入导出")
public class ExcelController {

    private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final SupplyItemService supplyItemService;

    @Operation(summary = "导出订单",hidden = true)
    @PostMapping("/export")
    public void export(@RequestBody OrderListQuery listQuery, HttpServletResponse response) throws IOException {

        List<SupplyItem> supplyItemList;
        if (listQuery.getIdList() != null && !listQuery.getIdList().isEmpty()) {
            supplyItemList = supplyItemService.lambdaQuery().in(SupplyItem::getId, listQuery.getIdList())
                    .orderByDesc(SupplyItem::getCreateTime)
                    .list();
        } else {
            supplyItemList = supplyItemService.lambdaQuery()
                    .eq(StringUtils.isNotBlank(listQuery.getOrderStatus()), SupplyItem::getOrderStatus, listQuery.getOrderStatus())
                    .eq(StringUtils.isNotBlank(listQuery.getItemOrderNo()), SupplyItem::getItemOrderNo, listQuery.getItemOrderNo())
                    .eq(StringUtils.isNotBlank(listQuery.getChildOrderNo()), SupplyItem::getChildOrderNo, listQuery.getChildOrderNo())
                    .eq(StringUtils.isNotBlank(listQuery.getSkuCode()), SupplyItem::getSkuCode, listQuery.getSkuCode())
                    .like(StringUtils.isNotBlank(listQuery.getGoodsName()), SupplyItem::getGoodsName, listQuery.getGoodsName())
                    .eq(StringUtils.isNotBlank(listQuery.getItemCode()), SupplyItem::getItemCode, listQuery.getItemCode())
                    .eq(StringUtils.isNotBlank(listQuery.getEnterprise()), SupplyItem::getEnterprise, listQuery.getEnterprise())
                    .ge(StringUtils.isNotBlank(listQuery.getStartDeliveryDate()), SupplyItem::getDeliveryDate, listQuery.getStartDeliveryDate())
                    .le(StringUtils.isNotBlank(listQuery.getEndDeliveryDate()), SupplyItem::getDeliveryDate, listQuery.getEndDeliveryDate())
                    .orderByDesc(SupplyItem::getCreateTime)
                    .list();
        }
        List<SupplyItemExcel> itemExcelList = supplyItemList.stream().map(item -> {
            SupplyItemExcel supplyItemExcel = new SupplyItemExcel();
            BeanUtils.copyProperties(item, supplyItemExcel);
            supplyItemExcel.setDeliveryDate(item.getDeliveryDate().format(timeFormatter));
            supplyItemExcel.setLeadOrderDate(item.getLeadOrderDate().format(timeFormatter));
            supplyItemExcel.setCreateTime(item.getCreateTime().format(timeFormatter));
            return supplyItemExcel;
        }).toList();


        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("代理发货订单信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        ClassPathResource classPathResource = new ClassPathResource("template/order.xlsx");
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .withTemplate(classPathResource.getInputStream())
                .build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            // 直接写入数据
            excelWriter.fill(itemExcelList, writeSheet);
        } catch (IOException e) {
            throw new RemoteException("导出失败,请稍后再试！");
        }
    }

    @Operation(summary = "订单导入",hidden = true)
    @PostMapping("/import")
    @Parameter(name = "file", description = "上传文件")
    public CommonResult<?> importExcel(@RequestParam MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return CommonResult.error("请检查文件是否为空");
        }

        List<SupplyItem> supplyItemList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), SupplyItemExcel.class, new PageReadListener<SupplyItemExcel>(dataList -> {
            dataList.forEach(data -> {
                SupplyItem supplyItem = new SupplyItem();
                BeanUtils.copyProperties(data, supplyItem);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(data.getDeliveryDate())) {
                    supplyItem.setDeliveryDate(LocalDateTime.parse(data.getDeliveryDate(), timeFormatter));
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(data.getLeadOrderDate())) {
                    supplyItem.setLeadOrderDate(LocalDateTime.parse(data.getLeadOrderDate(), timeFormatter));
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(data.getCreateTime())) {
                    supplyItem.setCreateTime(LocalDateTime.parse(data.getCreateTime(), timeFormatter));
                }
                supplyItem.setCreater(Long.valueOf(CustomToken.getAccountId()));
                supplyItemList.add(supplyItem);
            });
        })).sheet().doRead();
        if (supplyItemList.isEmpty()) {
            return CommonResult.error("请检查文件是否为空");
        }

        supplyItemService.saveBatch(supplyItemList);
        return CommonResult.success("导入成功");
    }


}
